
package it.csttech.date;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.ws.rs.BadRequestException;

import org.apache.commons.validator.routines.DateValidator;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * OVERVIEW This class provides a json deserializer for dates according to the
 * request locale
 * 
 * @author marcello.felappi
 * @author marco.dalena
 */
public class DateJsonDeserializer extends JsonDeserializer<Date> {

	/**
	 * Locale of the request
	 */
	private Locale locale;

	/**
	 * Empty constructor, needed by the framework to build the date serializer
	 * in the correct way.
	 * 
	 * @param locale
	 *            - the locale of the request
	 */
	public DateJsonDeserializer(Locale locale) {

		this.locale = locale;
	}

	/**
	 * This method is used to deserialize a date from a json message according
	 * to the locale of the request
	 * 
	 * @param parser
	 *            - JsonParser parser used by Jackson to parse the json input
	 * @param context
	 *            - DeserializationContext
	 * @throws IOException
	 *             - thrown due to i/o issues
	 * @throws JsonProcessingException
	 *             - thrown in case of problem during the parsing of the json
	 * @throws BadRequestException
	 *             - thrown because of an error during the parsing of the date
	 *             because of a wrong format
	 * @return the date deserialized from the string input
	 */
	@Override
	public Date deserialize(JsonParser parser, DeserializationContext context)
		throws IOException, JsonProcessingException {

		String input = parser.getText();
		DateFormat format =
			SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale);
		try {
			DateValidator validator = new DateValidator();
			if (validator.validate(
				input, ((SimpleDateFormat) format).toPattern(), locale) != null) {
				Date date = format.parse(input);

				return date;
			}
			else
				throw new BadRequestException();
		}
		catch (ParseException e) {
			throw new BadRequestException();
		}
	}

}
